package com.rdk.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.rdk.constant.StrConstant;
import com.rdk.entity.TUser;
import com.rdk.entity.TUserRelation;
import com.rdk.wechat.request.BaseWechatRquest;
import com.rdk.wechat.request.UserWechatRquest;
import com.rdk.wechat.request.impl.BaseWechatRquestImpl;
import com.rdk.wechat.request.impl.UserWechatRquestImpl;
import com.rdk.wechat.util.JSONutils;
import com.rdk.wechat.util.SystemConfig;

public class WechatInterfacesUtils {
	
	protected final static Log logger = LogFactory.getLog(WechatInterfacesUtils.class);
	
	private static BaseWechatRquest baseRquest;
	
	private static UserWechatRquest userRquest;
	
	/**
	 * 获取AccessToken
	 * @return
	 */
	public static String getAccessToken(){
		String accessToken = null;
		baseRquest = new BaseWechatRquestImpl();
		String app_id = SystemConfig.readValue("app_id");
		String app_secret = SystemConfig.readValue("app_secret");
		String client = SystemConfig.readValue("client");
		String jsonStr = baseRquest.getAccessToken(app_id, app_secret, client);
		if (StringUtil.isEmpty(jsonStr)){
			return accessToken;
		}
		Map<String, Object> map = JSONutils.json2Map(jsonStr);
		if ((int)map.get(StrConstant.JSON_CODE) == 0){
			Map<String, Object> mapTemp = (Map<String, Object>) map.get(StrConstant.JSON_RESULT);
			accessToken = (String)mapTemp.get("access_token");
			logger.debug("accessToken: " + accessToken);
		}else {
			String msg = (String)map.get(StrConstant.JSON_MSG);
			logger.error(msg);
		}
		return accessToken;
	}
	
	/**
	 * 获取userToken
	 * @param clinetKey
	 * @return
	 */
	public static String getUserToken(String clientKey, String accessToken){
		
		String userToken = null;
		userRquest = new UserWechatRquestImpl(accessToken);
		String jsonStr = userRquest.getUserToken(clientKey);
		
		if (StringUtil.isEmpty(jsonStr)){
			return userToken;
		}
		
		Map<String, Object> map = JSONutils.json2Map(jsonStr);
		if ((int)map.get(StrConstant.JSON_CODE) == 0){
			userToken = (String)map.get(StrConstant.JSON_RESULT);
			logger.debug("userToken: " + userToken);
		}else {
			String msg = (String)map.get(StrConstant.JSON_MSG);
			logger.error(msg);
		}
		
		return userToken;
	}
	
	/**
	 * 获取用户信息
	 * @param userToken
	 * @return
	 */
	public static TUser getUserInfo(String userToken, String accessToken){
		TUser user = new TUser();
		userRquest = new UserWechatRquestImpl(accessToken);
		String jsonStr = userRquest.getUserInfo(userToken, "zh_CN");
		
		if (StringUtil.isEmpty(jsonStr)){
			return user;
		}
		
		Map<String, Object> map = JSONutils.json2Map(jsonStr);
		if ((int)map.get(StrConstant.JSON_CODE) == 0){
			
			// {account=4395732358, name=尹明, sex=0, language=en, city=, province=, country=, headimgurl=http://test.linkdood.cn:10080/null}
			Map<String, Object> mTmep = (Map<String, Object>)map.get(StrConstant.JSON_RESULT);
			user.setUserId(mTmep.get("account").toString());
			user.setUserName(mTmep.get("name").toString());
			user.setSex(mTmep.get("sex").toString());
			user.setAvatar(mTmep.get("headimgurl").toString());
			logger.debug("TUser: " + user.toString());
		}else { 
			String msg = (String)map.get(StrConstant.JSON_MSG);
			logger.error(msg);
		}
		return user;
	}
	
	/**
	 * 获取用户好友列表时间戳
	 * 
	 * @param userToken
	 * @param accessToken
	 * @return
	 */
	public static List<Integer> getUserBuddysTimestamp(String userToken, String accessToken){
		List<Integer>  timestamps = new ArrayList<Integer>();
		userRquest = new UserWechatRquestImpl(accessToken);
		String jsonStr = userRquest.getUserBuddysTimestamp(userToken, "zh_CN");
		
		if (StringUtil.isEmpty(jsonStr)){
			return timestamps;
		}
		
		Map<String, Object> map = JSONutils.json2Map(jsonStr);
		if ((int)map.get(StrConstant.JSON_CODE) == 0){
			timestamps = (List<Integer>)map.get(StrConstant.JSON_RESULT);
		}else {
			String msg = (String)map.get(StrConstant.JSON_MSG);
			logger.error(msg);
		}
		return timestamps;
	}
	
	public static List<TUserRelation> getUserRelation(String userToken, String accessToken, String pageNo, String userId){
		List<TUserRelation> userRelationList = new ArrayList<TUserRelation>();
		userRquest = new UserWechatRquestImpl(accessToken);
		String jsonStr = userRquest.getUserBuddysToPaging(userToken, "zh_CN", pageNo);
		System.out.println(jsonStr);
		if (StringUtil.isEmpty(jsonStr)){
			return userRelationList;
		}
		Map<String, Object> map = JSONutils.json2Map(jsonStr);
		if ((int)map.get(StrConstant.JSON_CODE) == 0){
			List<Object> listTemp = (List<Object>)map.get(StrConstant.JSON_RESULT);
			
			for(int i = 0; i<listTemp.size(); i++){
				Map<String, Object> mapTemp = (Map<String, Object>)listTemp.get(i);
				TUser user = new TUser();
				String userName = String.valueOf(mapTemp.get("name"));
				user.setUserId(String.valueOf(mapTemp.get("userID")));
	            user.setUserName(userName);
	            
	            //判断用户名称是否为空
	            if(StringUtil.isNotEmpty(userName)){
	            	//取用户名称大写首字母
	            	user.setUserNameTag(PubFun.converterToFirstSpell(user.getUserName().substring(0, 1)).toUpperCase());
	            }
	            
	            user.setSex(String.valueOf(mapTemp.get("sex")));
	            // user.setBirthday(jsonObject.getString(""));
	            String url = String.valueOf(mapTemp.get("portraitURL"));
	            if (!url.startsWith("http")) {
	                url = SystemConfig.readValue("avatarUrl") + url;
	            }
	            user.setAvatar(url);

	            TUserRelation relation = new TUserRelation();
	            relation.setUserId(userId);
	            relation.setFriendUserId(user.getUserId());
	            relation.setUser(user);
	            relation.setGroupId(String.valueOf(mapTemp.get("groupID")));
	            relation.setPage((Integer)mapTemp.get("page"));
	            userRelationList.add(relation);
			}
			
		}else {
			String msg = map.get(StrConstant.JSON_MSG).toString();
			logger.error(msg);
		}
		
		return userRelationList;
	}
	
	public static void main(String[] args) {
		String a = null;
		String.valueOf(a);
		System.err.println(String.valueOf(a));
	}

}
